<template>
      <v-card flat title="设计SKU" style="height: 1000px;" v-loading="dialogLoading">
        <v-row>
          <v-col class="d-flex justify-space-between align-start">
            <!-- 元素图操作区 -->
            <v-card-item>
              <div class="element-img" v-show="curSku" style="display: flex;">
                <!-- 快捷区域 -->
                <div class="element-img__operate mr-6">
                  <div class="item" :class="{ 'active': curPos === 'front' }" @click="changePos('front')">
                    <img :src="curSku && curSku.frontBaseImage" alt="">
                  </div>
                  <div class="item" :class="{ 'active': curPos === 'back' }" @click="changePos('back')">
                    <img :src="curSku && curSku.backBaseImage" alt="">
                  </div>
                  <input class="color-picker" v-model="color" type="color">
                </div>
                <!--  裁剪区域 -->
                <div class="element-img__clipping">
                  <div class="container" :style="{'background-color': color}">
                    <!-- 底图 -->
                    <img v-if="curPos === 'front'" class="goods-img elevation-3" :src="curSku && curSku.frontBaseImage" alt="">
                    <img v-else class="goods-img elevation-3" :src="curSku && curSku.backBaseImage" alt="">
                    <!-- 蒙层 -->
                    <div ref="mask" id="mask" class="mask">
                      <canvas id="ele"></canvas>
                    </div>
                    <!-- 前元素图 -->
                    <img ref="frontImageEl" id="front-img" v-show="false" :src="skuGroup.frontImage" alt="">
                    <!-- 后元素图 -->
                    <img ref="backImageEl" id="back-img" v-show="false" :src="skuGroup.backImage" alt="">
                  </div>
                  <!-- 快捷操作区域 -->
                  <div class="element-img__operate d-flex justify-space-between pt-10">
                    <div class="d-flex gap-4" v-show="curSku">
                      <v-btn size="small" @click="openUpload">上传图片</v-btn>
                      <v-btn size="small" variant="outlined" @click="openStock">搜索图库</v-btn>
                    </div>
                    <div v-if="skuGroup.frontImage || skuGroup.backImage">
                      <!-- <div>快捷操作</div> -->
                      <div class="d-flex ga-4 mb-4">
                        <v-btn size="small" @click="fastMove('left')">靠左</v-btn>
                        <v-btn size="small" @click="fastMove('right')">靠右</v-btn>
                        <v-btn size="small" @click="fastMove('centerY')">垂直居中</v-btn>
                        <v-btn size="small" @click="fastMove('centerX')">水平居中</v-btn>
                      </div>
                      <div class="d-flex ga-4">
                        <v-btn size="small" @click="scaleElementImage(100)">100%</v-btn>
                        <v-btn size="small" @click="scaleElementImage(75)">75%</v-btn>
                        <v-btn size="small" @click="scaleElementImage(50)">50%</v-btn>
                        <v-btn size="small" @click="scaleElementImage(25)">25%</v-btn>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </v-card-item>
            <!-- 选中的规格 -->
            <v-card-item class="checked-sku">
              <AppTextField :disabled="mode === 'edit'" label="SKU编码" v-model="skuGroup.sn" multiple class="mb-4" placeholder="唯一编号" />
              <div class="mb-4">
                <v-btn-toggle style="height: 38px;" size="small" divided v-model="size" color="primary" variant="outlined">
                  <v-btn :value="item" v-for="item in sizes" :key="item">
                    {{ item }}
                  </v-btn>
                </v-btn-toggle>
              </div>
              <div class="mb-4">
                <v-btn size="small" @click="syncToSku">一键同步至所有规格</v-btn>
              </div>
            </v-card-item>
          </v-col>
        </v-row>
      </v-card>
    <!-- 上传图片 -->
    <upload-dialog ref="upload" @upload="uploadEleImg"></upload-dialog>
    <!-- 图库 -->
    <img-stock ref="stock" @checked="chooseEleImg"></img-stock>
  </template>
  
  <script setup>
  import {
    getThumbImg,
    getPodCategorySpec,
  } from "@/utils/index";
  import { nextTick, watch } from "vue";
  import { fabric } from "fabric";
  import imgStock from "./imgStock.vue";
  import uploadDialog from "./uploadDialog.vue";
import { walk } from "vue/compiler-sfc";
  
  const { proxy } = getCurrentInstance();
  
  const mode = ref("add");
  const dialogLoading = ref(false);
  const size = ref();
  const sizes = ref([]);
  const color = ref("#ffffff");
  const autofocus = ref(false);
  
  const props = defineProps({
    podCategoryId:Number,
  });

  const skuGroup = ref({
    podCategoryId: props.podCategoryId,
    sn: new Date().getTime(),
    frontImageId: "",
    backImageId: "",
    frontImage: "",
    backImage: "",
    skuList: [],
  });

  const emit = defineEmits(["update:modelValue"]);
  // 规格列表
  const podSpecList = ref([]);
  
  // 组件实例
  const upload = ref();
  const stock = ref();
  
  // 裁剪相关变量
  let canvas = null;
  let frontImgInstance = null;
  let backImgInstance = null;
  const curSku = ref(null);
  const curIndex = ref(0);
  const curPos = ref("front"); // front/back
  const mask = ref();
  const frontImageEl = ref();
  const backImageEl = ref();

  
  // 选中分类
  async function selectCategory() {
    console.log(props.podCategoryId)
    const res = await getPodCategorySpec({podCategoryId: skuGroup.value.podCategoryId});
    podSpecList.value = res.rows;


    skuGroup.value.skuList =  res.rows;
    // 新增时不需要传id
    skuGroup.value.skuList.forEach((sku) => {
      delete sku.id;
    });
    sizes.value = skuGroup.value.skuList.map((sku) => sku.size);
    // 新增组时，默认选中第一个尺码
    size.value = sizes.value[0];
  }
  selectCategory()

  // 打开上传
  function openUpload() {
    upload.value.visibleCircle = false;
    upload.value.visibleSku = false;
    upload.value.visible = true;
  }
  // 打开图库
  function openStock() {
    stock.value.open = true;
  }
  
  // 获取sku对应的蒙层和图片数据
  function getMaskAndBaseImage() {
    podSpecList.value.forEach((sku) => {
      if (sku.size === curSku.value.size) {
        curSku.value.frontBaseImage = sku.frontImage;
        curSku.value.backBaseImage = sku.backImage;
        curSku.value.frontMask = sku.frontMask;
        curSku.value.backMask = sku.backMask;
      }
    });
    renderMaskAndCanvas();
  }
  // 渲染蒙层和画布
  function renderMaskAndCanvas() {
    let maskPonits = curSku.value.frontMask.split(",");
    let width = maskPonits[2] + "px";
    let height = maskPonits[3] + "px";
    let top = maskPonits[1] + "px";
    let left = maskPonits[0] + "px";
    nextTick(() => {
      mask.value.style.width = width;
      mask.value.style.height = height;
      mask.value.style.top = top;
      mask.value.style.left = left;
      nextTick(() => {
        if (!canvas) {
          canvas = new fabric.Canvas("ele", {
            width: parseInt(mask.value.style.width),
            height: parseInt(mask.value.style.height),
          });
        } else {
          canvas.setWidth(parseInt(mask.value.style.width));
          canvas.setHeight(parseInt(mask.value.style.height));
          canvas.renderAll();
        }
        renderElementImage();
      });
    });
  }
  // 渲染元素图
  function renderElementImage() {
    if (skuGroup.value.frontImageId || skuGroup.value.backImageId) {
      if (canvas) {
        canvas.clear();
        canvas.renderAll();
      }
      if (frontImgInstance) {
        frontImgInstance = null;
      }
      if (backImgInstance) {
        backImgInstance = null;
      }
      drawEleImg();
    }
  }
  
  // 画元素图
  function drawEleImg() {
    let imageEl =
      curPos.value === "front" ? frontImageEl.value : backImageEl.value; // 元素图dom
    let maskWidth = mask.value.clientWidth;
    let top = 0;
    let left = 0;
    let width = 0;
    let height = 0;
    let range = [];
  
    // 有移动过元素图的情况
    if (curPos.value === "front" && curSku.value.frontImageRange) {
      let range = curSku.value.frontImageRange.split(",");
      left = range[0] * maskWidth;
      top = range[1] * maskWidth;
      width = range[2] * maskWidth;
      height = range[3] * maskWidth;
    } else if (curPos.value === "back" && curSku.value.backImageRange) {
      let range = curSku.value.backImageRange.split(",");
      left = range[0] * maskWidth;
      top = range[1] * maskWidth;
      width = range[2] * maskWidth;
      height = range[3] * maskWidth;
    }
    let imgInstance = null;
    if (curPos.value === "front") {
      if (!frontImgInstance) {
        frontImgInstance = new fabric.Image(imageEl, {
          left: left,
          top: top,
        });
      } else {
        frontImgInstance.set("top", top);
        frontImgInstance.set("left", left);
      }
      imgInstance = frontImgInstance;
    }
    if (curPos.value === "back") {
      if (!backImgInstance) {
        backImgInstance = new fabric.Image(imageEl, {
          left: left,
          top: top,
        });
      } else {
        backImgInstance.set("top", top);
        backImgInstance.set("left", left);
      }
      imgInstance = backImgInstance;
    }
  
    // 渲染元素图宽高 默认元素图和蒙层一样宽
    imgInstance.scaleToWidth(width || canvas.width);
    imgInstance.setControlVisible("mtr", false);
  
    let newTop = imgInstance.get("top");
    let newLeft = imgInstance.get("left");
    let newWidth = imgInstance.getScaledWidth();
    let newHeight = imgInstance.getScaledHeight();
    // 实时计算xywd
    function computedXYWD() {
      newTop = imgInstance.get("top");
      newLeft = imgInstance.get("left");
      newWidth = imgInstance.getScaledWidth();
      newHeight = imgInstance.getScaledHeight();
      console.log("newWidth", newWidth);
  
      range = [
        newLeft / maskWidth,
        newTop / maskWidth,
        newWidth / maskWidth,
        newHeight / maskWidth,
      ];
      range = range.map((el) => {
        return el.toFixed(3); // 保留三位小数
      });
      if (curPos.value === "front") {
        curSku.value.frontImageRange = range.join(",");
      } else {
        curSku.value.backImageRange = range.join(",");
      }
      skuGroup.value.skuList[curIndex.value] = curSku.value;
    }
  
    imgInstance.on("moving", () => {
      var canvasWidth = canvas.getWidth();
      var canvasHeight = canvas.getHeight();
      var imgWidth = imgInstance.getScaledWidth();
      var imgHeight = imgInstance.getScaledHeight();
      // 限制不能移出画布
      imgInstance.set({
        left: Math.min(canvasWidth - imgWidth, Math.max(imgInstance.left, 0)),
        top: Math.min(canvasHeight - imgHeight, Math.max(imgInstance.top, 0)),
      });
    });
  
    // 缩放事件
    imgInstance.on("scaling", (e) => {
      computedXYWD();
    });
    // 移动事件结束
    imgInstance.on("mouseup", () => {
      computedXYWD();
    });
    skuGroup.value.skuList[curIndex.value] = curSku.value;
    if (canvas) {
      canvas.add(imgInstance);
    } else {
      canvas.renderAll();
    }
  }
  // 计算素图坐标宽高
  function getElementRange(fabricImage) {
    let maskWidth = mask.value.clientWidth;
    let newTop = fabricImage.get("top");
    let newLeft = fabricImage.get("left");
    let newWidth = fabricImage.getScaledWidth();
    let newHeight = fabricImage.getScaledHeight();
  
    let range = [
      newLeft / maskWidth,
      newTop / maskWidth,
      newWidth / maskWidth,
      newHeight / maskWidth,
    ];
    range = range.map((el) => {
      return el.toFixed(3); // 保留三位小数
    });
    if (curPos.value === "front") {
      curSku.value.frontImageRange = range.join(",");
    } else {
      curSku.value.backImageRange = range.join(",");
    }
    skuGroup.value.skuList[curIndex.value] = curSku.value;
  }
  
  // 上传元素图
  function uploadEleImg(ids) {
    const id = ids[0];
    getThumbImg(id).then((base64) => {
      chooseEleImg({ id, base64 });
    });
  }
  
  // 选择元素图
  function chooseEleImg({ id, base64 }) {
    if (curPos.value === "front") {
      skuGroup.value.frontImageId = id;
      skuGroup.value.frontImage = base64;
      curSku.value.frontImageRange = "";
    } else {
      skuGroup.value.backImageId = id;
      skuGroup.value.backImage = base64;
      curSku.value.backImageRange = "";
    }
    nextTick(() => {
      renderElementImage();
    });
  }
  
  // 切换正反面
  function changePos(value) {
    curPos.value = value;
    // 切换正反面前，需清空画布的内容
    canvas.clear();
    // 已上传元素图后，才去重绘元素图
    if (curPos.value === "front" && skuGroup.value.frontImage) {
      renderElementImage();
    }
    if (curPos.value === "back" && skuGroup.value.backImage) {
      renderElementImage();
    }
  }
  
  //  将元素图信息同步至所有sku
  function syncToSku() {
    const frontImageRange = curSku.value.frontImageRange;
    const backImageRange = curSku.value.backImageRange;
    skuGroup.value.skuList.forEach((el) => {
      el.frontImageRange = frontImageRange;
      el.backImageRange = backImageRange;
    });
  }
  
  
  // 缩放的快捷操作
  function scaleElementImage(value) {
    const ratio = value / 100;
    const fabricImage =
      curPos.value === "front" ? frontImgInstance : backImgInstance;
    fabricImage.scaleToWidth(canvas.width * ratio);
    canvas.renderAll();
    getElementRange(fabricImage);
  }
  // 快速移动的快捷操作
  function fastMove(direction) {
    const fabricImage =
      curPos.value === "front" ? frontImgInstance : backImgInstance;
    if (direction === "centerX" || direction === "centerY") {
      moveObjectToCanvasCenter(fabricImage, direction);
    }
    if (direction === "left") {
      fabricImage.set("left", 0);
    }
    if (direction === "right") {
      moveObjectToCanvasRight(fabricImage);
    }
    canvas.renderAll(); // 重绘画布以显示更新后的对象位置
    getElementRange(fabricImage);
  }
  function moveObjectToCanvasCenter(obj, direction) {
    let canvasCenter = {
      x: canvas.width / 2,
      y: canvas.height / 2,
    };
    let objectCenter = {
      x: obj.getScaledWidth() / 2,
      y: obj.getScaledHeight() / 2,
    };
    if (direction === "centerY") {
      obj.set({
        top: canvasCenter.y - objectCenter.y,
      });
    }
    if (direction === "centerX") {
      obj.set({
        left: canvasCenter.x - objectCenter.x,
      });
    }
  }
  function moveObjectToCanvasRight(obj) {
    let distance = canvas.width - obj.getScaledWidth();
    obj.set("left", distance);
  }
  
  // 切换sku时获取对应sku的底图和蒙版
  watch([size], () => {
    if (size.value) {
      skuGroup.value.skuList.forEach((ele, index) => {
        if (ele.size === size.value) {
          curSku.value = ele;
          curIndex.value = index;
          getMaskAndBaseImage();
        }
      });
    } else {
      curSku.value = null;
    }
  });

  watch(skuGroup.value,(val)=>{
    emit('update:modelValue',val)
  })
  
  </script>
  
  <style lang="scss" scoped>
  .divA {
    background: yellow;
    height: 100px;
    width: 100px;
  }
  .divB {
    margin-top: 20px;
    background: rgb(105, 108, 243);
    height: 200px;
    width: 200px;
  }
  .element-img__operate {
    .item {
      background: #fff;
      border: 2px solid #e0e0e0;
      border-radius: 5px;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      overflow: hidden;
      img {
        max-width: 60px;
      }
    }
    .active {
      border-color: #757acc;
    }
    .color-picker {
      // width: 40px;
      // height: 40px;
      // border-radius: 100%;
      display: block;
      margin: 0 auto;
    }
  }
  .element-img__clipping {
    .container {
      position: relative;
      .goods-img {
        display: block;
      }
      .mask {
        position: absolute;
        top: 0;
        left: 0;
        border: 2px solid;
        box-sizing: content-box;
        // width: 200px;
        // height: 200px;
        // border: 2px solid;
        // position: absolute;
        // top: 0;
        // left: 0;
        // box-sizing: content-box;
        // .element {
        //   position: absolute;
        //   top: 0;
        //   left: 0;
        //   display: block;
        //   width: 100%;
        // }
      }
    }
  }
  </style>